package reverse_proxy

import (
	"context"
	"errors"
	"log"

	"gin-gateway/reverse_proxy/load_balance"
	"github.com/mwitkow/grpc-proxy/proxy"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

func NewGrpcLoadBalanceHandler(lb load_balance.LoadBalancer) grpc.StreamHandler {
	return func() grpc.StreamHandler {
		director := func(ctx context.Context, fullMethodName string) (context.Context, *grpc.ClientConn, error) {
			nextAddr, err := lb.Get("")
			// log.Printf("NewGrpcLoadBalanceHandler: nextAddr %s", nextAddr)
			if err != nil {
				return nil, nil, err
			}

			if nextAddr == "" {
				log.Println("NewGrpcLoadBalanceHandler: get next Addr fail")
				return nil, nil, errors.New("no endpoint available")
			}

			c, err := grpc.DialContext(ctx, nextAddr, grpc.WithCodec(proxy.Codec()), grpc.WithInsecure())
			md, _ := metadata.FromIncomingContext(ctx)
			outCtx := metadata.NewOutgoingContext(context.Background(), md.Copy())
			return outCtx, c, err
		}
		return proxy.TransparentHandler(director)
	}()
}
